<template>
  <div class="app-container">
    <el-card>
      <el-page-header @back="goBack">
        <template #content>
          <div class="flex items-center">
            <div v-if="!route.query?.id">新增覆膜日报单</div>
            <div v-else-if="route.query?.info">
              覆膜日报单{{ route.query?.audit ? "审核" : "详情" }}
              <el-tag>{{ form.coverNo }}</el-tag>
            </div>
            <div v-else>编辑覆膜日报单</div>
          </div>
        </template>
        <template #extra>
          <div class="flex items-center" v-if="!route.query.info">
            <el-button type="primary" :loading="btnLoading" @click="submitForm"
              >保 存</el-button
            >
          </div>
          <div class="flex items-center" v-if="route.query.audit">
            <el-button type="primary" @click="handleAudit">审 核</el-button>
          </div>
        </template>
      </el-page-header>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="基本信息" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">基本信息</span>
          </template>
          <div>
            <el-form
              :model="form"
              :rules="rules"
              :disabled="flag"
              ref="userRef"
              label-width="120px"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="日报日期" prop="orderDate">
                    <el-date-picker
                      style="width: 100%"
                      v-model="form.orderDate"
                      type="date"
                      placeholder="选择日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="机台" prop="machineName">
                    <el-input
                      v-model="form.machineName"
                      readonly
                      placeholder="请选择机台"
                      @click="openDialog"
                    />
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="8">
                                    <el-form-item label="机长" prop="userName">
                                        <el-input
                                            v-model="form.userName"
                                            readonly
                                            placeholder="自动带出"
                                        />
                                    </el-form-item>
                                </el-col> -->
                <el-col :span="8">
                  <el-form-item label="当班日期" prop="dutyDate">
                    <el-date-picker
                      style="width: 100%"
                      v-model="form.dutyDate"
                      type="date"
                      placeholder="选择日期"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <!-- <el-col :span="8">
                                    <el-form-item label="制单人" prop="createBy">
                                        <el-input
                                            v-model="form.createBy"
                                            readonly
                                            placeholder="自动带出"
                                        />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="装订方式" prop="mode">
                                        <el-input
                                            v-model="form.mode"
                                            placeholder="请输入装订方式"
                                        />
                                    </el-form-item>
                                </el-col> -->

                <el-col :span="8">
                  <el-form-item label="维修保养时长" prop="duration">
                    <el-input
                      v-model="form.duration"
                      placeholder="请输入维修保养时长"
                    >
                      <template #append>h</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="关联单据" prop="relatedOrder">
                    <el-input
                      v-model="form.relatedOrder"
                      readonly
                      placeholder="自动带出"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注">
                    <el-input
                      v-model="form.remark"
                      type="textarea"
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
        <!-- <el-collapse-item disabled  title="保养明细" name="2">
                    <template #title>
                        <el-icon style="color: #4479F6;">
                            <Position />
                        </el-icon> <span class="title">保养明细</span>
                    </template>
                    <div class="order-form">
                        <el-form :model="data" ref="reportCareListForm" :disabled="flag" class="data-form">
                            <el-table :data="data.reportCareList" border>
                                <el-table-column label="序号" width="60" type="index" align="center" />
                                <el-table-column label="保养单编码" width="300" prop="code" align="center">
                                </el-table-column>
                                <el-table-column label="时长(h)" width="150" prop="timeLength" align="center">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.timeLength" type="number" placeholder="请输入时长(h)">
                                            <template #append>h</template></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="备注" width="200" prop="remark" align="center">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.remark" placeholder="请输入内容"></el-input>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-form>
                    </div>
                </el-collapse-item> -->
        <el-collapse-item disabled title="人员明细" name="3">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">人员明细</span>
          </template>
          <el-button
            size="small"
            type="primary"
            style="margin-bottom: 10px"
            v-if="!route.query.info"
            @click="handleAddReportUserList"
          >
            选择人员
          </el-button>
          <div class="order-form">
            <el-form
              :model="data"
              ref="orderUserListForm"
              :disabled="flag"
              class="data-form"
            >
              <el-table
                :data="data.orderUserList"
                ref="orderUserListRef"
                border
                :header-cell-class-name="mustPeople"
                :row-class-name="tableRowClassName"
                :summary-method="getSummaries"
                show-summary
              >
                <el-table-column
                  label="序号"
                  width="60"
                  type="index"
                  align="center"
                />
                <el-table-column
                  label="员工工号"
                  min-width="160"
                  prop="userCode"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="员工姓名"
                  min-width="160"
                  prop="userName"
                  align="center"
                ></el-table-column>
                <!-- <el-table-column
                                    label="计时工资(元)"
                                    min-width="150"
                                    prop="timingWages"
                                    align="center"
                                >
                                    <template #default="scope">
                                        <el-form-item
                                            :prop="
                                                'orderUserList.' + scope.$index + '.timingWages'
                                            "
                                            :rules="[
                                                {
                                                    required: true,
                                                    message: '计时工资',
                                                    trigger: 'blur',
                                                },
                                            ]"
                                        >
                                            <el-input
                                                @blur="changeWagesSum(scope.row, scope.$index)"
                                                v-model="scope.row.timingWages"
                                                type="number"
                                                placeholder="请输入计时工资(元)"
                                            >
                                                <template #append>元</template>
                                            </el-input>
                                        </el-form-item>
                                    </template>
                                </el-table-column> -->
                <el-table-column
                  label="计件工资(元)"
                  min-width="150"
                  prop="piecePrice"
                  align="center"
                >
                  <template #default="scope">
                    <!-- <el-form-item
                      :prop="'orderUserList.' + scope.$index + '.piecePrice'"
                      :rules="[
                        {
                          required: true,
                          message: '计件工资',
                          trigger: 'blur',
                        },
                      ]"
                    > -->
                    <el-input
                      :disabled="flag"
                      v-model="scope.row.piecePrice"
                      type="number"
                      placeholder="请输入计件工资(元)"
                    >
                      <template #append>元</template>
                    </el-input>
                    <!-- </el-form-item> -->
                  </template>
                </el-table-column>
                <el-table-column
                  prop="proportion"
                  label="岗位占比"
                  align="center"
                >
                  <template #default="scope">
                    <el-input
                      type="number"
                      @input="limitInput('proportion', scope.row)"
                      :disabled="flag"
                      v-model="scope.row.proportion"
                    ></el-input>
                  </template>
                </el-table-column>
                <!-- <el-table-column
                                    label="补助工资(元)"
                                    min-width="160"
                                    prop="subsidyPrice"
                                    align="center"
                                >
                                    <template #default="scope">
                                        <el-form-item
                                            :prop="
                                                'orderUserList.' + scope.$index + '.subsidyPrice'
                                            "
                                            :rules="[
                                                {
                                                    required: true,
                                                    message: '计件工资',
                                                    trigger: 'blur',
                                                },
                                            ]"
                                        >
                                            <el-input
                                                @blur="changeWagesSum(scope.row, scope.$index)"
                                                v-model="scope.row.subsidyPrice"
                                                type="number"
                                                placeholder="请输入补助工资(元)"
                                            >
                                                <template #append>元</template>
                                            </el-input>
                                        </el-form-item>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    label="合计工资(元)"
                                    min-width="120"
                                    prop="sumPrice"
                                    align="center"
                                ></el-table-column> -->
                <el-table-column
                  label="操作"
                  v-if="!flag"
                  align="center"
                  fixed="right"
                  class-name="small-padding fixed-width"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      icon="Delete"
                      @click="handleDelete(scope.row)"
                    ></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item disabled title="完成工作量明细" name="4">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">完成工作量明细</span>
            <!-- <el-button
              v-if="route.query?.audit"
              style="margin-left: 10px"
              size="small"
              type="danger"
              @click="handleReport"
            >
              质量事故上报
            </el-button> -->
          </template>
          <el-button
            size="small"
            type="primary"
            style="margin-bottom: 10px"
            v-if="!route.query.info"
            @click="handleAddPieceList"
          >
            选择生产单
          </el-button>
          <div class="order-form">
            <el-form :model="data" ref="orderWorkListForm" class="data-form">
              <el-table
                :data="data.orderWorkList"
                ref="orderWorkListRef"
                border
                height="600px"
                :header-cell-class-name="mustReport"
                :summary-method="getSummariesWorkList"
                show-summary
              >
                <el-table-column
                  label="序号"
                  width="60"
                  type="index"
                  align="center"
                />
                <!-- <el-table-column
                                    label="类型"
                                    align="center"
                                    width="80"
                                    :show-overflow-tooltip="true"
                                    prop="type"
                                >
                                    <template v-slot="{ row }">
                                        <el-tag
                                            :type="row.type == 1 ? 'success' : ''"
                                            effect="dark"
                                        >
                                            {{ row.type == 1 ? '封面' : '内文' }}
                                        </el-tag>
                                    </template>
                                </el-table-column> -->
                <el-table-column
                  label="生产单编码"
                  min-width="150"
                  align="center"
                  :show-overflow-tooltip="true"
                  prop="produceNo"
                ></el-table-column>
                <!-- <el-table-column
                  label="产品信息"
                  min-width="150"
                  align="center"
                  :show-overflow-tooltip="true"
                  prop="produceCode"
                ></el-table-column> -->
                <el-table-column
                  label="下单日期"
                  min-width="120"
                  align="center"
                  :show-overflow-tooltip="true"
                  prop="submitDate"
                >
                  <template v-slot="{ row }">
                    {{ row.submitDate ? row.submitDate.split("T")[0] : "" }}
                  </template>
                </el-table-column>
                <el-table-column
                  label="品种"
                  min-width="150"
                  align="center"
                  prop="breedType"
                ></el-table-column>
                <el-table-column
                  label="组成"
                  min-width="150"
                  align="center"
                  prop="composition"
                ></el-table-column>
                <el-table-column
                  label="规格型号"
                  min-width="150"
                  align="center"
                  prop="specification"
                >
                  <template #default="scope">
                    <dict-tag
                      :options="mes_paper_specs"
                      :value="scope.row.specification"
                    />
                  </template>
                </el-table-column>
                <!-- <el-table-column
                  label="覆膜尺寸"
                  min-width="150"
                  align="center"
                  :show-overflow-tooltip="true"
                  prop="coveringSize"
                ></el-table-column>
                <el-table-column
                  label="成品尺寸"
                  min-width="150"
                  align="center"
                  :show-overflow-tooltip="true"
                  prop="finishedProduct_size"
                ></el-table-column> -->
                <!-- <el-table-column
                  label="覆膜令数"
                  min-width="150"
                  align="center"
                 
                  prop="ream"
                ></el-table-column> -->
                <el-table-column
                  label="覆膜张数"
                  min-width="120"
                  align="center"
                  prop="coveringPageNum"
                >
                </el-table-column>
                <el-table-column
                  label="完工数量"
                  min-width="120"
                  align="center"
                  prop="completeCount"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'orderWorkList.' + scope.$index + '.completeCount'"
                      :rules="[
                        {
                          required: true,
                          message: '完成数量',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        @mousewheel.prevent
                        :disabled="flag"
                        @blur="changeCompleteCount(scope.row, scope.$index)"
                        v-model="scope.row.completeCount"
                        type="number"
                        placeholder="请输入完成数量"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="计件令数"
                  min-width="120"
                  align="center"
                  prop="pieceReam"
                >
                  <!-- <template #default="scope">
                                        <el-input
                                            @blur="changePieceLing(scope.row, scope.$index)"
                                            v-model="scope.row.pieceReam"
                                            type="number"
                                            placeholder="请输入计件令数"
                                        ></el-input>
                                    </template> -->
                </el-table-column>
                <el-table-column
                  label="计件标准"
                  min-width="120"
                  align="center"
                  prop="pieceStandard"
                >
                  <template #default="scope">
                    <el-form-item
                      :prop="'orderWorkList.' + scope.$index + '.pieceStandard'"
                      :rules="[
                        {
                          required: true,
                          message: '计件标准',
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-input
                        @mousewheel.prevent
                        :disabled="flag"
                        @blur="changePieceLing(scope.row, scope.$index)"
                        v-model="scope.row.pieceStandard"
                        type="number"
                        placeholder="请输入计件标准"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="计件金额"
                  align="center"
                  prop="piecePrice"
                ></el-table-column>
                <el-table-column
                  label="最大允许上报数量"
                  align="center"
                  prop="maxNum"
                ></el-table-column>
                <el-table-column
                  label="备注"
                  width="150"
                  prop="remark"
                  align="center"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.remark"
                      placeholder="请输入内容"
                    ></el-input>
                  </template>
                </el-table-column>
                <!-- <el-table-column
                  v-if="route.query.audit"
                  label="事故原因"
                  width="150"
                  prop="reason"
                  align="center"
                ></el-table-column> -->
                <el-table-column
                  label="操作"
                  v-if="!route.query.info"
                  align="center"
                  fixed="right"
                  class-name="small-padding fixed-width"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="primary"
                      icon="Delete"
                      @click="handleDeleteOrder(scope.row)"
                    ></el-button>
                  </template>
                </el-table-column>
                <!-- <el-table-column
                  label="操作"
                  width="120"
                  v-if="route.query.audit"
                  align="center"
                  fixed="right"
                  class-name="small-padding fixed-width"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="danger"
                      @click="handleSingleReport(scope.row)"
                    >
                      质量事故上报
                    </el-button>
                  </template>
                </el-table-column> -->
              </el-table>
            </el-form>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <SearchWorkBench
      :visible="searchVisible"
      @changeUpdate="changeWorkBenchData"
      :search="{ type: '7' }"
      @cancel="
        () => {
          searchVisible = false;
        }
      "
    ></SearchWorkBench>
    <userWorkListVue
      :visible="searchPeopleVisible"
      :userWorkList="userWorkList"
      @changeUpdate="changePeopleData"
      @cancel="
        () => {
          searchPeopleVisible = false;
        }
      "
    ></userWorkListVue>
    <pieceList
      :visible="pieceListOpen"
      :params="params"
      @changeUpdate="changePieceListData"
      :orderSelectList="orderSelectList"
      @cancel="
        () => {
          pieceListOpen = false;
        }
      "
    ></pieceList>
  </div>
</template>

<script setup>
import {
  addCover,
  getCoverById,
  listReportCare,
  updateStatus,
} from "@/api/production/coverReport.js";
import SearchWorkBench from "@/components/SearchWorkBench";
import userWorkListVue from "@/components/userWorkList";
import useTagsViewStore from "@/store/modules/tagsView";
import useUserStore from "@/store/modules/user";
import pieceList from "./pieceList.vue";
import { toNumber } from "@/utils/ruoyi";
import { nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
const route = useRoute();
const router = useRouter();
const searchVisible = ref(false);
const searchPeopleVisible = ref(false);
const pieceListOpen = ref(false);
const tagsViewStore = useTagsViewStore();
const { proxy } = getCurrentInstance();
const userInfo = useUserStore();
const peopleSelectList = ref([]);
const orderSelectList = ref([]);
const activeNames = ["1", "2", "3", "4"];
const userRef = ref(null);
const orderUserListForm = ref(null);
const orderWorkListForm = ref(null);
const flag = ref(false);
const sumPriceSum = ref(0);
const totalAmount = ref(0);
const totalAmountH = ref(0);
const userWorkList = ref([]);
const params = ref({});
const btnLoading = ref(false);
const data = reactive({
  reportCareList: [], // 保养
  orderUserList: [], // 人员
  orderWorkList: [], // 完成
  form: {
    type: "1",
  },
  rules: {
    machineName: [{ required: true, message: "机台不能为空", trigger: "blur" }],
    orderDate: [
      { required: true, message: "报工日期不能为空", trigger: "blur" },
    ],
  },
});
nextTick(() => {
  form.value.createBy = userInfo.name;
});
const {
  mes_paper_package,
  mes_paper_specs,
  ems_order_print_color,
  ems_produce_book_size,
  ems_order_binding_mode,
} = proxy.useDict(
  "mes_paper_package",
  "ems_order_print_color",
  "ems_produce_book_size",
  "ems_order_binding_mode",
  "mes_paper_specs"
);
const { form, rules, reportCareList, orderUserList, orderWorkList } =
  toRefs(data);
if (route.query?.id) {
  getCoverById({ pid: route.query.id }).then((res) => {
    Object.assign(form.value, { ...res.data });
    params.value = { machineId: res.data.machineId, type: 7 };
    // reportCareList.value = res.data.reportCareList
    orderUserList.value = res.data.orderUserList;
    orderWorkList.value = res.data.orderWorkList;
    if (route.query.info) {
      flag.value = true;
    }
  });
}
// 合计
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (!values.every((value) => Number.isNaN(value))) {
      sums[index] = `${values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return toNumber(prev + curr, 2);
        } else {
          return toNumber(prev, 2);
        }
      }, 0)}`;
      if (column.property == "piecePrice") {
        sumPriceSum.value = toNumber(Number(sums[index]), 2);
      }
    } else {
      sums[index] = "";
    }
  });
  return sums;
};
// 合计
const getSummariesWorkList = (param) => {
  const { columns, data } = param;
  const sums = [];
  const fieldsToSum = ["piecePrice", "piecePriceH"];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    if (fieldsToSum.includes(column.property)) {
      const values = data.map((item) => Number(item[column.property]));
      if (!values.every((value) => Number.isNaN(value))) {
        sums[index] = `${values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!Number.isNaN(value)) {
            return toNumber(prev + curr, 2);
          } else {
            return toNumber(prev, 2);
          }
        }, 0)}`;
        if (column.property == "piecePrice") {
          totalAmount.value = toNumber(Number(sums[index]), 2);
        }
      } else {
        sums[index] = "";
      }
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

function limitInput(key, row) {
  row[key] =
    ("" + row[key]) // 第一步：转成字符串
      .replace(/[^\d^\.]+/g, "")
      .replace(/^0+(\d)/, "$1")
      .replace(/^\./, "0.")
      .match(/^\d*(\.?\d{0,1})/g)[0] || "";
  handleTotalCount();
}
const handleTotalCount = () => {
  // 计算计件工资
  const totalLing = orderWorkList.value.reduce((prev, item) => {
    prev += Number(item.piecePrice || 0);
    return prev;
  }, 0);
  const totalProportion = orderUserList.value.reduce((prev, item) => {
    prev += Number(item.proportion || 0);
    return prev;
  }, 0);
  orderUserList.value.forEach((item) => {
    if (item.proportion) {
      item.piecePrice = toNumber(
        (Number(item.proportion) / totalProportion) * totalLing,
        2
      );
    }
  });
};
const mustPeople = (obj) => {
  let mustColumns = [3, 4];
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};

const mustReport = (obj) => {
  let mustColumns = [7, 9];
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};
// 令数等于完工数量除1000
const changeCompleteCount = (row, index) => {
  if (orderWorkList.value[index].completeCount <= 0) {
    orderWorkList.value[index].completeCount = null;
    return ElMessage({
      message: `完成数量不能小于0`,
      type: "warning",
    });
  } else if (
    orderWorkList.value[index].completeCount > orderWorkList.value[index].maxNum
  ) {
    orderWorkList.value[index].completeCount = null;
    return ElMessage({
      message:
        "完成数量不能大于最大允许上报数量" + orderWorkList.value[index].maxNum,
      type: "warning",
    });
  }
  orderWorkList.value[index].pieceReam = toNumber(
    Number(row.completeCount || 0) / 1000,
    2
  );
  changePieceLing(row, index);
};
// 获取当前时间
const getCurrentDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  form.value.orderDate = `${year}-${month}-${day} `;
};
getCurrentDateTime();
// 打开机台页面
const openDialog = () => {
  searchVisible.value = true;
};
// 选择人员
const handleAddReportUserList = () => {
  peopleSelectList.value = orderUserList.value;
  searchPeopleVisible.value = true;
};
// 选中的机台
const changeWorkBenchData = (row) => {
  orderUserList.value = [];
  orderWorkList.value = [];
  userWorkList.value = row.mesMachineUserList.map((item) => {
    return {
      ...item,
      name: item.mesUsers.name,
      code: item.mesUsers.code,
    };
  });
  form.value.machineName = row.machineName;
  form.value.machineId = row.pid;
  params.value = { machineId: form.value.machineId };
  // form.value.userName = row.headUserName
  listReportCare({ status: 2, machineNo: row.machineNo }).then((res) => {
    form.value.relatedOrder = res.data[0]?.code;
    // reportCareList.value = res.data.map(item => {
    //     return {
    //         code: item.code,
    //         timeLength: undefined,
    //         remark: undefined,
    //     }
    // })
  });
  searchVisible.value = false;
};
// 选中的人员
const changePeopleData = (row) => {
  const codeSet = new Set(orderUserList.value.map((data) => data.id));
  row.forEach((item) => {
    if (!codeSet.has(item.id)) {
      orderUserList.value.push({
        ...item,
        remark: null,
        userCode: item.code,
        userName: item.name,
        piecePrice: null,
        subsidyPrice: null,
      });
      codeSet.add(item.id);
    }
  });
  orderUserList.value = orderUserList.value.filter((item) =>
    row.some((rowItem) => rowItem.id === item.id)
  );
  if (orderWorkList.value.length > 0) {
    handleTotalCount();
  }
  searchPeopleVisible.value = false;
};
// 合计工资
const changeWagesSum = (row, index) => {
  orderUserList.value[index].sumPrice =
    Number(row.piecePrice) + Number(row.subsidyPrice);
};
// 删除
const handleDelete = (row) => {
  proxy.$modal.confirm("是否确认删除该数据？").then(function () {
    orderUserList.value = orderUserList.value.filter(
      (item) => item.id !== row.id
    );
    handleTotalCount();
    proxy.$modal.msgSuccess("删除成功");
  });
};
const handleDeleteOrder = (row) => {
  proxy.$modal.confirm("是否确认删除该数据？").then(function () {
    orderWorkList.value = orderWorkList.value.filter((item) =>
      item.pid ? item.pid !== row.pid : item.pieceId != row.pieceId
    );
    handleTotalCount();
    proxy.$modal.msgSuccess("删除成功");
  });
};

// 选择生产单
const handleAddPieceList = () => {
  if (!form.value.machineId) {
    return ElMessage({
      message: "请先选择机台",
      type: "warning",
    });
  }
  orderSelectList.value = orderWorkList.value;
  pieceListOpen.value = true;
};
// 选中的数据
const changePieceListData = (row) => {
  const codeSet = new Set(orderWorkList.value.map((data) => data.pieceId));
  row.forEach((item) => {
    if (!codeSet.has(item.pieceId)) {
      orderWorkList.value.push({
        ...item,
        totalNum: item.totalNum, //
        lossCoefficient: item.lossCoefficient, //损耗系数
        lxjf: item.lxjf, //另行加放
        pieceReam: item.pieceReam, //计件令数
        fromType: "1", // 来源类型  1生产单， 2纸张
        bookCode: item.bookNo,
        orderName: item.bookName,
        labeling: item.pieceView,
        pieceStandard: 9.5, //计件标准
      });
      codeSet.add(item.pieceId);
    }
  });
  pieceListOpen.value = false;
};
// 计算计件令数
const changePieceLing = (row, index) => {
  // if (
  //     Number(orderWorkList.value[index].completeCount) +
  //         Number(orderWorkList.value[index].totalNum) >
  //     Number(orderWorkList.value[index].maxNum)
  // ) {
  //     orderWorkList.value[index].completeCount = undefined
  //     return ElMessage({
  //         message: '完工数量+累计已上报数量不能大于最大允许上报数量',
  //         type: 'success',
  //     })
  // }
  //debugger;
  // //0610 修改
  // //覆膜：如果印刷的累计上报量<1000,计件令数=1-（印数-本次允许最大上报量）/1000，如果印刷的累计上报量>=1000,计件令数=完成/1000
  // if (
  //   Number(row.totalNum || 0) < 1000 &&
  //   Number(row.maxNum || 0) * 0.99 <= Number(row.completeCount || 0)
  // ) {
  //   //item.pieceLing =1;
  //   row.SJNum = Number(row.coveringPageNum || 0) - Number(row.maxNum || 0);
  //   row.SJNum = row.SJNum < 0 ? 0 : row.SJNum;
  //   orderWorkList.value[index].pieceReam = toNumber(1 - row.SJNum / 1000, 4);
  // } else {
  //   // 完工数量/1000 * 印张
  //   orderWorkList.value[index].pieceReam = toNumber(
  //     Number(row.completeCount || 0) / 1000,
  //     4
  //   );
  // }

  //0618
  // 完工数量/1000 * 印张
  orderWorkList.value[index].pieceReam = toNumber(
    Number(row.completeCount || 0) / 1000,
    4
  );
  if (orderWorkList.value[index].pieceReam < 1) {
    orderWorkList.value[index].pieceReam = 1;
  }

  orderWorkList.value[index].piecePrice = toNumber(
    (Number(orderWorkList.value[index].pieceReam) || 0) *
      (Number(row.pieceStandard) || 0),
    2
  );
  // changeAmount()
  handleTotalCount();
};
// //  计算计件金额
// const changeAmount = (row, index) => {
//     // 计件令数*计件标准
//     orderWorkList.value[index].piecePrice = toNumber(
//         (Number(row.pieceLing) || 0) * (Number(row.pieceStandard) || 0),
//         2
//     )
// }
// //  计算计件金额（换版）
// const changeAmountH = (row, index) => {
//     // 换版数量*计件标准（换版）
//     orderWorkList.value[index].piecePriceH = toNumber(
//         (Number(row.exchangeNum) || 0) * (Number(row.pieceStandardH) || 0),
//         2
//     )
// }
//  返回
// 质量上报
const handleReport = () => {
  ElMessageBox.prompt("请输入质量原因", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    inputPattern: /^.+$/,
    inputErrorMessage: "请输入质量原因",
  })
    .then(({ value }) => {
      orderWorkList.value.forEach((item) => {
        item.reason = value;
        item.accident = "1";
      });
    })
    .catch(() => {});
};
// 单个上报
const handleSingleReport = (row) => {
  ElMessageBox.prompt("请输入质量原因", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    inputPattern: /^.+$/,
    inputErrorMessage: "请输入质量原因",
  })
    .then(({ value }) => {
      row.reason = value;
      row.accident = "1";
      // updateStatus({ pid: row.pid, voidReason: value, status: 0 }).then(res => {
      //     getList()
      //     proxy.$modal.msgSuccess('作废成功')
      // })
    })
    .catch(() => {});
};

const goBack = () => {
  // router.replace({ path: "/production/coverReport" });
  // setTimeout(() => {
  //   tagsViewStore.delView(route);
  // }, 0);
  setTimeout(() => {
    router.go(-1);
    tagsViewStore.delView(route);
  }, 0);
};

// 清除主键
const clearId = (list, key) => {
  if (list.length > 0) {
    list.forEach((item) => {
      delete item[key];
    });
  }
};
// 保存
const submitForm = async () => {
  btnLoading.value = true;
  try {
    await userRef.value.validate();
    // await orderUserListForm.value.validate()
    // if (Number(sumPriceSum.value) != Number(totalAmount.value)) {
    //   return ElMessage({
    //     message: "合计工资与计件金额不符",
    //     type: "warning",
    //   });
    // }

    await orderWorkListForm.value.validate();
    if (orderWorkList.value.length > 0) {
      const invalidItem = orderWorkList.value.findIndex(
        (item) => item.completeCount <= 0 || item.pieceStandard <= 0
      );

      if (invalidItem !== -1) {
        btnLoading.value = false;
        return ElMessage({
          message: `第${invalidItem + 1}行的完成数量或计件标准不能小于等于0`,
          type: "warning",
        });
      }
    }

    if (orderUserList.value != null && orderUserList.value.length == 0) {
      btnLoading.value = false;
      return ElMessage({
        message: "请填写人员明细",
        type: "warning",
      });
    }

    if (orderWorkList.value != null && orderWorkList.value.length == 0) {
      btnLoading.value = false;

      return ElMessage({
        message: "请填写完成工作量明细",
        type: "warning",
      });
    }
    clearId(orderUserList.value, "id");
    if (route.query?.id) {
      clearId(orderWorkList.value, "id");
      await addCover({
        ...form.value,
        // reportCareList: reportCareList.value,
        orderUserList: orderUserList.value,
        orderWorkList: orderWorkList.value,
      });
      ElMessage({
        message: "编辑成功",
        type: "success",
      });
      goBack();
    } else {
      // 新增
      form.value.status = 0; //0:未审核 1：已审核  2：审核未通过
      await addCover({
        ...form.value,
        orderUserList: orderUserList.value,
        orderWorkList: orderWorkList.value,
      });
      ElMessage({
        message: "新增成功",
        type: "success",
      });
      goBack();
    }
  } catch (error) {
    btnLoading.value = false;

    if (Object.keys(error)?.join(",").includes(".")) {
      const errInfoList = Object.values(error);
      const err = [];
      errInfoList.forEach((item) => {
        err.push(item[0].message);
      });
      ElMessage({
        message: `请将${err.join("、")}信息补充完整`,
        type: "warning",
      });
    }
  }
};
// 审核
const handleAudit = () => {
  clearId(orderUserList.value, "id");
  clearId(orderWorkList.value, "id");
  //20240613
  updateStatus({ status: 1, pid: form.value.pid }).then((res) => {
    ElMessage({
      message: "审核成功",
      type: "success",
    });
    goBack();
  });
  // addCover({
  //   ...form.value,
  //   orderUserList: orderUserList.value,
  //   orderWorkList: orderWorkList.value,
  // }).then((res) => {
  //   updateStatus({ status: 1, pid: form.value.pid }).then((res) => {
  //     ElMessage({
  //       message: "审核成功",
  //       type: "success",
  //     });
  //     goBack();
  //   });
  // });
};
</script>

<style lang="scss" scoped>
.order-form :deep(.el-form-item) {
  margin-bottom: 0px;
}

:deep(.el-table th.must div:before) {
  content: "*";
  color: #ff1818;
}

:deep(.el-table) .success-row {
  background: #dae5f4 !important;
}
</style>
